function initContainerSize() {
  var BASE_WIDTH = 1920;
  var BASE_HEIGHT = 1080;
  var windowHeight = document.body.clientHeight;
  var windowWidth = document.body.clientWidth;
  window.ratio = BASE_WIDTH / windowWidth;
  var myCanvas = {}
  if ((windowWidth / windowHeight) > (BASE_WIDTH / BASE_HEIGHT)) {
    myCanvas.Width = windowHeight * BASE_WIDTH / BASE_HEIGHT;
    myCanvas.Height = windowHeight;
    myCanvas.Top = (windowHeight - myCanvas.Height) / 2;
    myCanvas.Left = (windowWidth - myCanvas.Width) / 2;
  } else {
    myCanvas.Width = windowWidth;
    myCanvas.Height = windowWidth * BASE_HEIGHT / BASE_WIDTH;
    myCanvas.Top = (windowHeight - myCanvas.Height) / 2;
    myCanvas.Left = (windowWidth - myCanvas.Width) / 2;
  }
  $('#mainSvg,#myVideo,#loading').css({
    width: myCanvas.Width,
    height: myCanvas.Height,
    left: '50%',
    top: '50%',
    'margin-left': -myCanvas.Width / 2,
    'margin-top': -myCanvas.Height / 2,
    position: 'absolute'
  });
}

window.onresize = function () {
  initContainerSize();
}

initContainerSize();

var video = document.querySelector('#myVideo');
var audio = document.querySelector('#myAudio');
var videoTotalTime = 0;
var progressWidth = 710;
var beforeTime = -1;
var playRate = 1.0;
var mainSvg = document.querySelector('#mainSvg');
var progressBar = document.querySelector('#progressBar');
var btnProgressBar = document.querySelector('#btnProgressBar');
var myPlayer = videojs(video, {
    poster: window.config.video.poster,
    sources: [
      {
        src: window.config.video.src,
        type: window.config.video.type
      }
    ]
  },
  function onPlayerReady() {
    setTimeout(function () {
      videoTotalTime = Math.round(myPlayer.remainingTime());
      $('#txtTotalTime').text(timeFormat(videoTotalTime));
    }, 200);
    this.on('ended', function () {
      mediaPause();
    });
    this.on(`timeupdate`, progress);
  });
videojs.addLanguage('zh-CN');
var loadingMt = setTimeout(function () {
  if (videoTotalTime > 0) {
    $('#loading').removeClass('active');
    clearTimeout(loadingMt);
  }
}, 1000);
// 设置标题
document.title = window.config.title;

/**
 * 播放按钮
 */
$('#btnPlay').click(function (event) {
  mediaPlay();
  event.preventDefault();
});
/**
 * 暂停按钮
 */
$('#btnPause').click(function (event) {
  mediaPause();
  event.preventDefault();
});
var barW = 0;

// 播放进度
function progress() {
  var currentTime = Math.round(myPlayer.currentTime());
  barW = Math.floor((currentTime / videoTotalTime * progressWidth));
  changeProgressBar(barW || 0);
  $('#txtCurrentTime').text(timeFormat(currentTime));
  if (beforeTime !== currentTime) {
    beforeTime = currentTime;
    showSubtitle(currentTime);
  }
}

// 修改播放进度
function changeProgressBar(val) {
  btnProgressBar.setAttribute('x', val);
  progressBar.setAttribute('width', val);
}

var flagMouseDown = false;
var oldX = 0;
var rw = 0;
var mt = null;
var isPaused = false;
var isMute = false;
// 拖拽
// btnProgressBar.addEventListener('mousedown', function (e) {
//   // console.log('down', e.clientX);
//   isPaused = myPlayer.paused;
//   oldX = e.offsetX;
//   mediaPause();
//   clearTimeout(mt);
//   rw = progressBar.getAttribute('width') * 1;
//   flagMouseDown = true;
// });
//
// btnProgressBar.addEventListener('mouseup', function () {
//   clearTimeout(mt);
//   mediaPause();
//   flagMouseDown = false;
// });
//
// mainSvg.addEventListener('mouseup', function (e) {
//   if (!$(e.target).hasClass('img-btn')) {
//     resetVideo();
//   }
// });
// mainSvg.addEventListener('mouseleave', function (e) {
//   resetVideo();
// });
// mainSvg.addEventListener('mousemove', function (e) {
//   if (flagMouseDown) {
//     clearTimeout(mt);
//     myPlayer.volume(0);
//     var nx = (e.offsetX - oldX) * window.ratio + rw;
//     var x = Math.floor((nx / progressWidth) * videoTotalTime);
//     if (x === 0) {
//       x = myPlayer.currentTime();
//     }
//     (x >= 0 && x <= videoTotalTime) && myPlayer.currentTime(x);
//     mediaPlay();
//     mt = setTimeout(function () {
//       mediaPause();
//     }, 500);
//   }
// });

function resetVideo() {
  if (flagMouseDown) {
    flagMouseDown = false;
    myPlayer.volume(isMute ? 0 : 1);
    clearTimeout(mt);
    isPaused ? mediaPause() : mediaPlay();
  }
}

// 时间格式化
function timeFormat(t) {
  var m = Math.floor(t / 60),
    s = Math.floor(t % 60);
  m = m < 10 ? '0' + m : m;
  s = s < 10 ? '0' + s : s;
  return m + ':' + s
}

// 播放速度切换
$('.btn-play_rate').click(function (event) {
  var val = $(this).data('val');
  $(this).addClass('active').siblings().removeClass('active');
  playRate = val;
  myPlayer.playbackRate(val);
  event.preventDefault();
});

// 静音
$('#btnSound').click(function (event) {
  console.log('btnSound', !myPlayer.volume())
  !myPlayer.volume() ?
    (myPlayer.volume(1), $('#btnSound').removeClass('off'), isMute = false)
    :
    (myPlayer.volume(0), $('#btnSound').addClass('off'), isMute = true);
  event.preventDefault();
});
// 字幕
$('#btnWord').click(function () {
  $('#gWord').hasClass('hidden') ?
    ($('#gWord').removeClass('hidden'), $('#btnWord').removeClass('off'))
    :
    ($('#gWord').addClass('hidden'), $('#btnWord').addClass('off'));
});
// 帮助
$('#btnHelp').click(function () {
  $('#gHelp').addClass('active');
});
// 关闭帮助
$('#btnCloseHelp').click(function () {
  $('#gHelp').removeClass('active');
});

// 字幕列表
var subtitles = window.config.subtitles || [];
var subtitlesHtmls = []
subtitles.forEach(function (e) {
  subtitlesHtmls.push('<image class="img-word" data-duration="' + e.duration + '" id="imgWord_' + e.time + '" data-time="' + e.time + '" xlink:href="' + e.img + '" x="0" y="0" width="1920" height="1080"/>')
})
$('#gWord').html(subtitlesHtmls.join(''));

/**
 * 字幕控制
 */
function showSubtitle(currentTime) {
  var currentSubtitle = $('#imgWord_' + currentTime);
  if (currentSubtitle.length) {
    var duration = currentSubtitle.data('duration')
    currentSubtitle.addClass('active').siblings().removeClass('active');
    setTimeout(function () {
      currentSubtitle.removeClass('active');
    }, duration * 1000 * playRate);
  }
}

function mediaPlay() {
  myPlayer.play();
  playAudio();
  $('#btnP').addClass('play').removeClass('pause');
}

function mediaPause() {
  myPlayer.pause();
  pauseAudio();
  $('#btnP').addClass('pause').removeClass('play');
}

function playAudio() {
  audio.play();
}

function pauseAudio() {
  audio.pause();
}
